// fasttime 模块，扩展 chrono 时间功能

/// 微秒相关的常量和工具函数
pub mod a8_micros {
    /// 一毫秒的微秒数
    pub const MICROS_PER_MILLIS: u64 = 1_000;
}

/// 为 NaiveTime 添加扩展方法
pub mod b2_time {
    use chrono::{Timelike, NaiveTime};
    
    /// 为 NaiveTime 添加的扩展方法
    pub trait TimeExt {
        /// 获取微秒值
        fn micros_of_day(&self) -> u64;
        
        /// 从微秒创建时间
        fn from_micros_day_unsafe(micros: u64) -> NaiveTime;
        
        /// 从小时、分钟、秒、毫秒创建时间
        fn from_hmsi_friendly_unsafe(millis: u64) -> NaiveTime;

        fn hour_minute(&self) -> u32;
        
        fn to_string6(&self) -> String;

        fn to_string3(&self) -> String;
    }
    
    impl TimeExt for NaiveTime {
        fn micros_of_day(&self) -> u64 {
            // 计算当日微秒数，使用 Timelike trait 的公开方法
            let hour = self.hour() as u64;
            let minute = self.minute() as u64;
            let second = self.second() as u64;
            let nano = self.nanosecond() as u64; // 公开的 nanosecond 方法
            let micro = nano / 1000; // 纳秒转微秒
            
            (hour * 3600 + minute * 60 + second) * 1_000_000 + micro
        }
        
        fn from_micros_day_unsafe(micros: u64) -> NaiveTime {
            let seconds = (micros / 1_000_000) as u32;
            let micros_remainder = (micros % 1_000_000) as u32;
            let nanos = micros_remainder * 1000; // 微秒转纳秒
            
            let hours = seconds / 3600;
            let minutes = (seconds % 3600) / 60;
            let seconds = seconds % 60;
            
            NaiveTime::from_hms_nano_opt(hours, minutes, seconds, nanos).unwrap_or_default()
        }
        
        fn from_hmsi_friendly_unsafe(millis: u64) -> NaiveTime {
            let micros = millis * crate::fasttime::a8_micros::MICROS_PER_MILLIS;
            Self::from_micros_day_unsafe(micros)
        }

        fn hour_minute(&self) -> u32 {
            self.hour() * 100 + self.minute()
        }

        fn to_string6(&self) -> String {
            self.format("%H:%M:%S.%6f").to_string()
        }
        
        fn to_string3(&self) -> String {
            self.format("%H:%M:%S.%3f").to_string()
        }
    }
}
